import { useState } from "react";
import { Text } from "react-native";

import Dialog from "@/components/Dialog";
import type { Props as DialogProps } from "@/components/Dialog";

export type Option = Omit<DialogProps, "visible" | "children" | "onDismiss"> & {
  /** 点击遮罩回调 */
  onDismiss?: () => void | Error;
  /** 内容文本 */
  text?: string;
  /** 内容渲染组件 */
  contentComponent?: () => React.ReactNode;
};

let tempOpt: Option | null = null;
export default () => {
  const [state, _setState] = useState<Option & { visible: boolean }>({
    visible: false
  });

  // 通用更新状态(单个)
  const setState = (field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  };

  const onDismiss = () => {
    const res = tempOpt?.onDismiss?.();
    if (!(res instanceof Error)) {
      hide();
    }
  };

  const hide = () => setState("visible", false);

  const show = (opt: Option) => {
    tempOpt = opt;
    _setState({
      ...opt,
      visible: true
    });
    return hide;
  };

  // 组件
  const Comp = (
    <Dialog {...state} onDismiss={onDismiss}>
      {state.text ? <Text>{state.text}</Text> : ""}
      {tempOpt?.contentComponent && tempOpt.contentComponent()}
    </Dialog>
  );

  return {
    Dialog: Comp,
    show,
    hide
  };
};
